#include <stdio.h>
#include <stdlib.h>

typedef struct LNode{
	int data;
	struct LNode *next; /*指向链表下一个结点*/
}LNode,*LinkList;

/*顺序插入到链表当中*/
void CreateLinkListReverse(LinkList head,int n){ 
	int data;
	int i;
	LinkList p,q;
	q = head;
	printf("Please input %d characters,separated by space:",n);
	for(i = 1; i <= n; ++i){
		scanf("%d",&data);
		p = (LinkList)malloc(sizeof(LNode));
		p->data = data;
		p->next = NULL;
		q->next = p;
		q = p;
	}
}
/*找出倒数第m个数*/
LinkList LinkListCountDownNumber(LinkList head,int m){
	int i;
	LinkList p = head->next;
	for(i = 1; i <= m; ++i){/*找到顺数第m个元素*/
		if(p)
			p = p->next;
		else
			return NULL;
	}
	LinkList q = head->next;
	while(p){/*p和q结点之间相差m个元素，当p到达链表尾部的时候，q则是倒数第m个结点*/
		q = q->next;
		p = p->next;
	}
	return q;
}

/*打印出链表中所有数据*/
void LinkListPrint(LinkList head){
	LinkList p = head->next;
	while(p){
		printf("%d ",p->data);
		p = p->next;
	}
}

int main(){
	int n,m;
	LinkList p;
	LinkList head = (LinkList)malloc(sizeof(LNode)); /*定义头结点*/
	head->next = NULL;
	printf("Please input the length of LinkList:");
	scanf("%d",&n);
	CreateLinkListReverse(head,n);
	printf("Please input countdown number:");
	scanf("%d",&m);
	p = LinkListCountDownNumber(head,m);
	if(!p)
		printf("Cannot find countdown number of %d(m>n).\n",m);
	else	
		printf("Find countdown number of %d is %d.\n",m,p->data);
	/*LinkListPrint(head);*/
	return 0;
}